var params = app.getRequestParams();

$(function(){

    app.request({
        url:'store/select?transfer=1',
        success:function (resp) {
            initPage(resp.data);
        }
    });


});
var backEditFlag = true;
function initPage(storeData) {
    layer.load();
    $('#fixtable').fixgrid({
        bottom:'none',scroll:true,
        columns:[
            [
                {field:'serialnumber',title:'',width:30},
                {field:'o',title:'操作',width:60,formatter:function () {
                        return gridOpt('#fixtable');
                    }},
                {
                    field:'productId',
                    title:'<span class="red">*</span>商品 -- 扫描枪录入<span init="off" style="position: relative;cursor: pointer;" id="productTitleIcon"></span>',
                    width:200,
                    editor:'search',
                    searchData:function(that){
                        return $(that).parent().data().product;
                    },
                    click:datagridSearchClick,
                    url:'../../common/product_list.html',
                    editBefore:editBefore
                }
            ],
            [
                {field:'unitId',title:'单位',width:80,editor:'combobox',editBefore:editBefore,
                    getData:function(cell,callback){
                        var rowData = cell.parent().data().product;
                        app.request({
                            url:'product/getMultiUnit',
                            data:{productId:rowData.id},
                            success:function (resp) {
                                var comboData = [{id:rowData.unitId,name:rowData.unitName}];
                                comboData.merge(resp.data);
                                callback(comboData);
                            }
                        });
                    },comboboxData:function (that) {
                        return $(that).data();
                    }
                },
                {field:'number',title:'<span class="red">*</span>调拨数量',width:80,editor:'decimal',editBefore:editBefore},
                {field:'outStoreId',title:'<span class="red">*</span>调出仓库',width:120,editor:'combobox',editBefore:editBefore,
                    getData:function(cell,callback){
                        return callback(storeData);
                    },comboboxData:function (that) {
                        return $(that).data();
                    }
                },
                {field:'outPrice',title:'<span class="red">*</span>调出单价',width:120,editor:'decimal',editBefore:editBefore},
                {field:'inStoreId',title:'<span class="red">*</span>调入仓库',width:120,editor:'combobox',editBefore:editBefore,
                    getData:function(cell,callback){
                        return callback(storeData);
                    },comboboxData:function (that) {
                        return $(that).data();
                    }
                },
                {field:'inPrice',title:'<span class="red">*</span>调入单价',width:120,editor:'decimal',editBefore:editBefore},
                {field:'remarks',title:'备注',width:180,editBefore:editBefore,editor:'text'}
            ]
        ]
    });

    initButtons({service:'transfer',htmlName:'transfer',orderText:'调拨',codePrefix:'DB',orderType:0});

    laydate.render({
        elem: '#order_date',value:app.getServerDate()
    });

    // 必须放在最后  所有代码要写在之前
    if(params.id){
        app.request({
            url:'transfer/getOrder',
            data:{id:params.id},
            success:function (resp) {
                
                initEdit(resp.data);
                layer.closeAll('loading');
            }
        });
    }else{
        $('#order_title').html('新增调拨单');
        for(var i=0 ; i < 5 ; i++){createRow();}
        layer.closeAll('loading');
    }
}

//编辑初始化
function initEdit(data){
    var details = data.details;
    var order = data.order;
    
    init_edit_buttons(order);
    
    $('#order_title').html('编辑调拨单[ DB'+order.code+' ]');

    $('#order_date').val(app.time2str(parseInt(order.date)));
    $('textarea[name="order.remarks"]').val(order.remarks);
    
    for (var i=0 ; i<details.length ; i++){
        var detail = details[i];
        init_edit_detail(detail,i);
    }

}

function init_edit_detail(detail,i) {
    var product = {};
    product.id = detail.productId;
    product.name = detail.productName;
    createRow();
    var leftRow = $('#fixtable .ctx-left .vui-table .vui-table-row').eq(i);
    var rightRow = $('#fixtable .ctx-right .vui-table .vui-table-row').eq(i);
    var searchCell = leftRow.find('.vui-table-cell[field="productId"]');
    searchCell.data({product:product});
    searchCell.html(product.name);
    leftRow.data({product:product});
    rightRow.data({product:product});
    rightRow.find('.vui-table-cell[field="unitId"]').html(detail.unitName).data({value:detail.unitId,text:detail.unitName});
    rightRow.find('.vui-table-cell[field="number"]').html(app.div(detail.number,app.DIV).replace('.00',''));
    
    rightRow.find('.vui-table-cell[field="outStoreId"]').html(detail.outStoreName).data({value:detail.outStoreId,text:detail.outStoreName});
    rightRow.find('.vui-table-cell[field="inStoreId"]').html(detail.inStoreName).data({value:detail.inStoreId,text:detail.inStoreName});
   
    rightRow.find('.vui-table-cell[field="outPrice"]').html(app.div(detail.outPrice,app.DIV));
    rightRow.find('.vui-table-cell[field="inPrice"]').html(app.div(detail.inPrice,app.DIV));
    rightRow.find('.vui-table-cell[field="remarks"]').html(detail.remarks);
    
    
}

//表单检查
var details = [];
var checkRowsTip = false;
function checkForm(){
    checkRowsTip = false;
    var checkOptions = [
        {type:'input',name:'order.date',verify:[{type:'required'}]}
    ];

    if(app.checkForm(checkOptions)){
        checkRows();
        if(checkRowsTip)return false;
        if(details.length == 0){
            app.msg(layer,'至少填写一条商品记录',2);
            return false;
        }else{
            return true;
        }
    }

    return false;
}

//保存
var accounts = [];
function saveAction(saveType,obj){
    var data = app.serializeForm();
    data.saveType = saveType;
    data['order.date'] =new Date(data['order.date']).getTime();

    $.each(details,function(i,row){
        for ( var n in row ){
            data["details["+i+"]."+n] = row[n];
            data["details["+i+"].ord"] = i;
        }
    });

    var url = 'transfer/insert';

    if(params.id){
        data['order.id'] = params.id;
        url = 'transfer/update';
    }

    doSave(url,data,saveType,obj);

}

function checkOrderDataChange() {
    return true;
}

function checkRows() {
    details = [];
    $('#fixtable .ctx-left .vui-table-row').each(function () {
        var product = getRowEleProduct($(this));
        if( product && product.id ){
            var n = $(this).attr('i');
            //body区域对应行
            var bodyTr = $('#fixtable .ctx-right .vui-table-row').eq(n);

            var detail = {productId:product.id};
            //仓库
            var outStore = getField(bodyTr,'outStoreId').data();
            if( !outStore.value ){
                app.msg(layer,'商品【'+product.name+'】未选择调出仓库',2);
                checkRowsTip = true;
                return false;
            }
            detail.outStoreId = outStore.value;detail.outCompanyId = -1;
            var inStore = getField(bodyTr,'inStoreId').data();
            if( !inStore.value ){
                app.msg(layer,'商品【'+product.name+'】未选择调入仓库',2);
                checkRowsTip = true;
                return false;
            }
            detail.inStoreId = inStore.value;detail.inCompanyId = -1;

            // 单位
            var unitNameData = getField(bodyTr,'unitId').data();
            detail.unitId = unitNameData.value;
            detail.unitMain = unitNameData.main ? 1 : 0;
            // 单价
            var outPriceStr = getField(bodyTr,'outPrice').html();
            if( outPriceStr==null || outPriceStr.length == 0 ){
                app.msg(layer,'商品【'+product.name+'】未填写调出单价',2);
                checkRowsTip = true;
                return false;
            }
            detail.outPrice = app.mul(outPriceStr,app.DIV,0);

            var inPriceStr = getField(bodyTr,'inPrice').html();
            if( inPriceStr==null || inPriceStr.length == 0 ){
                app.msg(layer,'商品【'+product.name+'】未填写调入单价',2);
                checkRowsTip = true;
                return false;
            }
            detail.inPrice = app.mul(inPriceStr,app.DIV,0);
            // 数量
            detail.number = app.mul(getField(bodyTr,'number').html(),app.DIV,0);
            // 备注
            detail.remarks = getField(bodyTr,'remarks').html();
            details.push(detail);
        }
    });
}

//商品选择后
function productSelected(cell){
    var obj = productSelectedCommon(cell);
    var product = obj.product;
    var rightRow = obj.rightRow;

    rightRow.find('.vui-table-cell[field="unitId"]').html(product.unitName).data({value:product.unitId,text:product.unitName});
    rightRow.find('.vui-table-cell[field="number"]').html(1);

}


